package com.liuyfly.leetcode.questions;

import com.liuyfly.leetcode.model.ListNode;
import com.liuyfly.leetcode.util.LeetcodeUtil;

/**
 * @author liuyangfang at 2022-09-04 16:46
 */
public class Question0021 {
    /**
     * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
     * <pre>
     * 示例 1：
     * 输入：l1 = [1,2,4], l2 = [1,3,4]
     * 输出：[1,1,2,3,4,4]
     * </pre>
     * <pre>
     * 示例 2：
     * 输入：l1 = [], l2 = []
     * 输出：[]
     * </pre>
     * <pre>
     * 示例 3：
     * 输入：l1 = [], l2 = [0]
     * 输出：[0]
     * </pre><br/>
     * <br/>
     * 链接：https://leetcode.cn/problems/merge-two-sorted-lists
     */
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        } else if (list2 == null) {
            return list1;
        }
        ListNode head = new ListNode();
        ListNode newCurrent = head;
        ListNode current1 = list1;
        ListNode current2 = list2;
        if (current1.val < current2.val) {
            head.val = current1.val;
            current1 = current1.next;
        } else {
            head.val = current2.val;
            current2 = current2.next;
        }

        while (current1 != null || current2 != null) {
            ListNode newListNode = new ListNode();
            if (current1 == null) {
                newListNode.val = current2.val;
                current2 = current2.next;
            } else if (current2 == null) {
                newListNode.val = current1.val;
                current1 = current1.next;
            } else if (current1.val < current2.val) {
                newListNode.val = current1.val;
                current1 = current1.next;
            } else {
                newListNode.val = current2.val;
                current2 = current2.next;
            }
            newCurrent.next = newListNode;
            newCurrent = newListNode;
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode node1 = LeetcodeUtil.initSortedListNode(5);
        LeetcodeUtil.printListNode(node1);
        ListNode node2 = LeetcodeUtil.initSortedListNode(5);
        LeetcodeUtil.printListNode(node2);

        ListNode result = mergeTwoLists(node1, node2);
        LeetcodeUtil.printListNode(result);
    }
}
